<?php
namespace app\admin2\controller;

use think\Db;
use think\Session;
use app\common\model\Qrcode as QrcodeModel;
use app\common\model\WxUser as WxUserModel;
use app\common\util\WechatThirdUtil;
use app\common\controller\AdminBaseo;

class Qrcode extends AdminBaseo
{
    private $author_wx_user;
    private $qrcode_model;
    protected $third_config;
    protected $wx_user_model;
    protected $wechat_obj;

    protected function _initialize(){
        parent::_initialize();
        $this->wx_user_model = new WxUserModel;
        $this->qrcode_model = new QrcodeModel;
        $this->author_wx_user = Session::get('wechat_info');
        $this->third_config = $this->wx_user_model->find(); //第三方开发平台信息
        $this->wechat_obj = new WechatThirdUtil($this->third_config , $this->author_wx_user);
    }

    public function qrcode(){
        $qrcode_list = $this->qrcode_model->where('auid',$this->author_wx_user['id'])->select();
        if($qrcode_list){
            return json(['status' => 1 , 'msg' => 'ok' , 'qrcode_list' => $qrcode_list]);
        }else{
            return json(['status' => -1 , 'error' => 'qrlist error']);
        }
    }

    /**
     * 添加临时二维码
     */
    public function add(){
        return $this->fetch();
    }

    public function saveTempQrcode(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $scene_id = $this->qrcode_model->where('auid',$this->author_wx_user['id'])->count();
            $qrcode_id  = $data['create'] == 0 ? 'UDDPHA'.$scene_id : $data['qrcode_id'];
            if ($data['type'] == 'QR_LIMIT_SCENE') {//永久二维码
                $result = $this->wechat_obj->createPermQrcode($scene_id);
            }else if ($data['type'] == 'QR_SCENE') {
                $result = $this->wechat_obj->createTempQrcode($data['expire'], $scene_id);
            }
            
            if($result){
                $file = $this->wechat_obj->showQrcode($result['ticket']);
                $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
                $filename = $this->savePath($upload_path);
                // 检测目录
                if (false === $this->checkPath($filename)) {
                    return false;
                }
                $save_path   = '/uploads/'; 
                $name = md5(microtime(true)).'.jpg';

                if($file){
                    $filename_path = $filename. $name;
                    $save_result = $this->saveweixinFile($filename_path,$file['body']);
                    if($save_result){
                            $path = str_replace('\\', '/', $save_path . date('Ymd') . DS . $name);
                            $data['url'] = $result['url'];
                            $data['qrcode'] = $path;
                            $data['auid'] = $this->author_wx_user['id'];
                            $data['qrcode_id'] = $qrcode_id;
                            $data['scene_id'] = $scene_id;
                            $save_result = $this->qrcode_model->allowField(true)->save($data);
                            if($save_result){
                                return json(['status' => 1 , 'msg' => 'ok']);
                            }else{
                                return json(['status' => -1 , 'error' => 'set qrcode failed']);
                            }
                    }else{
                        return json(['status' => -1 , 'error' => 'qrcode resource failed']);
                    }
                }
            }
        }
    }

    /**
     * 文件保存至本地
     */
    private function saveweixinFile($filename , $filecontent){
        $local_file = fopen($filename , 'w');
        if(false !== $local_file){
            if(false !== fwrite($local_file,$filecontent)){
                fclose($local_file);
                return true;
            }
        }
        return false;
    }

    private function savePath($path){
        $rule = "date";
        $path = rtrim($path, DS) . DS;
        switch($rule){
            case 'date' : 
                $saveName = date('Ymd') . DS;
                break;
        }
        $filename = $path . $saveName;
        return $filename;
    }

    private function checkPath($path)
    {
        if (is_dir($path)) {
            return true;
        }

        if (mkdir($path, 0755, true)) {
            return true;
        } else {
            $this->error = "目录 {$path} 创建失败！";
            return false;
        }
    }

    public function index(){
        $result = $this->qrcode_model->where('auid',$this->author_wx_user['id'])->select();
        $this->assign('info',$result);
        return $this->fetch();
    }

    public function openAndClose(){
        $data = $this->request->post();
        if($data['type'] == 'true'){
            if($this->qrcode_model->where('auid',$this->author_wx_user['id'])->where('is_open',1)->find()){
                return json(['status'=>2,'msg'=>'只允许开启一个']);
            }
            $result = $this->qrcode_model->save(['is_open'=>1],['id'=>$data['contro_id'],'auid'=>$this->author_wx_user['id']]);
            if($result){
                return json(['status'=>1,'msg'=>'开启成功']);
            }else{
                return json(['status'=>2,'msg'=>'开启失败']);
            }
        }else{
            $result = $this->qrcode_model->save(['is_open'=>0],['id'=>$data['contro_id'],'auid'=>$this->author_wx_user['id']]);
            if($result){
                return json(['status'=>1,'msg'=>'关闭成功']);
            }else{
                return json(['status'=>2,'msg'=>'关闭失败']);
            }
        }
    }

    public function getQrList(){
        $qr_list = $this->qrcode_model->query('SELECT `scene_id`,`name` FROM `think_qrcode` WHERE (`create_time` + `expire`) > unix_timestamp(now()) OR `expire` IS NULL');
        if($qr_list) return json(['status'=>1,'msg'=>'ok' , 'qr_list' => $qr_list]);
        return json(['status' => -1,'error'=>'get qrlist failed']);
    }
}